package com.bw.mvicore.ui

import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.bw.common.common.WSMsgType
import com.bw.common.event.WSReceiveEvent
import com.bw.common.utils.LogUtils
import com.bw.common.utils.NotificationUtils
import com.bw.common.utils.UserUtils
import com.bw.mvicore.common.ConstantValue
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * @author:created by hahajing
 * 时间：2024/4/22 0022
 * 企鹅号:444511958
 * 描述:
 */
abstract class BaseActivity : AppCompatActivity() {
    protected val handler: Handler = Handler(Looper.getMainLooper())
    private lateinit var netBroadCastReceiver:NetBroadCastReceiver
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(generateContentView())

        val list = listOf<Int>(1)
//        BarUtils.setStatusBarColor(this, Color.GRAY,false)
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
        initView()
        registerNetBroadCastReceiver()
        /**
         * 注册eventbus
         */
        EventBus.getDefault().register(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveWSMsg(event:WSReceiveEvent){
        if (event.type==WSMsgType.RECEIVE){
            //解构
            var (msg,packagename,action) = event.msg.split(",")
            var user = UserUtils.getUserFromStr(msg)
            val utils = NotificationUtils(this, com.bw.common.R.mipmap.ic_launcher,"主播上线","您关注的主播[${user.username}]上线了，快来围观~")
            val intent = Intent(this,NotificationReceiver::class.java)
            intent.putExtra("user",user.username)
            intent.putExtra("packagename",packagename)
            intent.putExtra("action",action)
            utils.notifiedBroadcast(intent)
        }
        handleReceiveWSMsg(event)
    }

    /**
     * 交给子类处理接收到的WebSocket消息
     */
    open fun handleReceiveWSMsg(event: WSReceiveEvent){}

    override fun onResume() {
        super.onResume()
        initData()
        initEvent()
    }

    override fun onDestroy() {
        super.onDestroy()
    }



    override fun onStop() {
        super.onStop()
        releaseRes()
        /**
         * 注销网络状态相关的广播接收者 避免泄露
         */
        if (::netBroadCastReceiver.isInitialized){
            LocalBroadcastManager.getInstance(this).unregisterReceiver(netBroadCastReceiver)
        }

        /**
         * 注销EventBus
         */
        EventBus.getDefault().unregister(this)
    }

    /**
     * 释放资源
     */
    abstract fun releaseRes()

    /**
     * 初始化视图
     */
    protected open fun initView() {

    }

    /**
     * 创建content view
     */
    abstract fun generateContentView(): View

    /**
     * 初始化加载数据
     */
    abstract fun initData()

    /**
     * 初始化事件
     */
    abstract fun initEvent()

    /**
     * 发送消息
     */
    fun showMsg(msg: String) =
        if (Looper.getMainLooper().thread != Thread.currentThread()) {
            handler.post {
                showMsgReal(msg)
            }
        } else {
            showMsgReal(msg)
        }



    /**
     * 页面路由
     */
    fun route(target:Class<*>){
        startActivity(Intent(this@BaseActivity,target))
    }

    /**
     * 页面路由隐式跳转
     */
    fun route(packagename:String,action:String){
        val intent = Intent()
        intent.`package`= packagename
        intent.action = action
        startActivity(intent)
    }

    /**
     * 页面路由（带参数）
     */
    fun route(taget:Class<*>,params:Bundle){
        val intent=Intent(this@BaseActivity,taget)
        intent.putExtra(ConstantValue.PARAMS,params)
        startActivity(intent)
    }

    /**
     *  创建基于Started生命周期的协程作用域
     *  method - 要执行的方法
     */
    fun generateLifeCycleLaunch(method:suspend ()->Unit){
        lifecycleScope.launch(Dispatchers.IO) {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
               method()
            }
        }
    }


    private fun showMsgReal(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }

    /**
     * 注册网络状态相关的广播接收者
     */
    private fun registerNetBroadCastReceiver() {
        netBroadCastReceiver = NetBroadCastReceiver()

        val filter = IntentFilter()
        filter.addAction(com.bw.common.common.ConstantValue.NET_ERR_401)
        filter.addAction(com.bw.common.common.ConstantValue.NET_ERR_403)
        filter.addAction(com.bw.common.common.ConstantValue.NET_ERR_404)
        filter.addAction(com.bw.common.common.ConstantValue.NET_ERR_500)
        LocalBroadcastManager.getInstance(this).registerReceiver(netBroadCastReceiver,filter)
    }

    /**
     * 关闭当前activity
     */
    fun closeThiz(){
        finish()
    }

    /**
     * 替换fragment
     */
    fun replaceFragment(containerId:Int,fragment:Fragment){
        supportFragmentManager.beginTransaction()
            .replace(containerId,fragment)
            .commitAllowingStateLoss()
    }

    /**
     * 添加fragment
     */
    fun addFragment(fragment: Fragment,tag:String){
        supportFragmentManager.beginTransaction()
            .add(fragment,tag)
            .commitAllowingStateLoss()
    }

    fun addFragment(fragment: Fragment,containerId:Int){
        supportFragmentManager.beginTransaction()
            .add(containerId,fragment)
            .commitAllowingStateLoss()
    }

    /**
     * 显示指定的Fragment
     */
    fun showFragment(fragment:Fragment){
        supportFragmentManager.beginTransaction().show(fragment).commitAllowingStateLoss()
    }

    /**
     * 隐藏指定的Fragment
     */
    fun hideFragment(fragment: Fragment){
        supportFragmentManager.beginTransaction().hide(fragment).commitAllowingStateLoss()
    }

    /**
     * 对应网络状态的广播接收者
     */
    inner class NetBroadCastReceiver:BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent?.action
            when(action){
                com.bw.common.common.ConstantValue.NET_ERR_401->{
                    LogUtils.d("BaseActivity","get broadcast net_err_401")
                    route("com.bw.ivideo","com.bw.ivideo.mine.login")
                }
                com.bw.common.common.ConstantValue.NET_ERR_404->{

                }
                com.bw.common.common.ConstantValue.NET_ERR_403->{

                }
                com.bw.common.common.ConstantValue.NET_ERR_500->{

                }
            }
        }

    }

    class NotificationReceiver constructor() :BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            val user= intent?.getStringExtra("user")
            val packagename = intent?.getStringExtra("packagename")
            val action = intent?.getStringExtra("action")
            val intent = Intent()
            intent.setComponent(ComponentName("com.bw.ivideo","com.bw.live.ui.LiveActivity"))
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            val bundle = Bundle()
            bundle.putBoolean("isBoradcastr",false)
            intent.putExtra("params",bundle)
            context?.startActivity(intent)
        }

        companion object{

        }

    }

}